﻿using AutoMapper;
using MediatR;
using Work.API.Applications.Write.Commands;
using Work.API.Dtos;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;
using Yitter.IdGenerator;

namespace Work.API.Applications.Write.CommandHandlers
{
    /// <summary>
    /// 就诊人添加(办理医疗卡)
    /// </summary>
    public class AddPatientCommandHandler : IRequestHandler<AddPatientCommand, ApiResult<AddPatientResultDto>>
    {
        private readonly IBaseRepository<Patient> patientRep;
        private readonly IMapper mapper;

        public AddPatientCommandHandler(IBaseRepository<Patient> patientRep,IMapper mapper)
        {
            this.patientRep = patientRep;
            this.mapper = mapper;
        }
        public async Task<ApiResult<AddPatientResultDto>> Handle(AddPatientCommand request, CancellationToken cancellationToken)
        {
            ApiResult<AddPatientResultDto> result = new ApiResult<AddPatientResultDto>();

            var entity = mapper.Map<Patient>(request);
            entity.CardNumber = DateTime.Now.ToString("yyyyMMddHHmmss");
            var rows = await patientRep.AddAsync(entity);
            if(rows > 0)
            {
                result.Code = ApiEnum.成功;
                result.Message = ApiEnum.成功.ToString();
                result.Data = new AddPatientResultDto
                {
                    PatientId = entity.PatientId,
                    CardNumber = entity.CardNumber
                };
            }
            else
            {
                result.Code = ApiEnum.失败;
                result.Message = ApiEnum.失败.ToString();
                result.Data = new AddPatientResultDto();
            }
            return result;
        }

    }
}
